package pers.qianyu.month_202101.date_20210114;

import java.util.*;

/**
 * 350. 两个数组的交集 II
 * https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
 *
 * @author mizzle rain
 * @date 2021-01-14 17:07
 */
public class Intersect {
    public int[] intersect(int[] nums1, int[] nums2) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int n : nums1) {
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        ArrayList<Integer> res = new ArrayList<>();
        for (int n : nums2) {
            if (map.containsKey(n)) {
                Integer count = map.get(n);
                res.add(n);
                count--;
                if (count == 0) {
                    map.remove(n);
                } else {
                    map.put(n, count);
                }
            }
        }
        int[] arr = new int[res.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = res.get(i);
        }
        return arr;
    }
}
